package com.martain.leetcode.t66;

import java.util.LinkedList;

/**
 * 给出集合[1,2,3,...,n]，其所有元素共有n! 种排列。
 *
 * 按大小顺序列出所有排列情况，并一一标记，当n = 3 时, 所有排列如下：
 *
 * "123"
 * "132"
 * "213"
 * "231"
 * "312"
 * "321"
 * 给定n 和k，返回第k个排列。
 *
 * 
 *
 * 示例 1：
 *
 * 输入：n = 3, k = 3
 * 输出："213"
 * 示例 2：
 *
 * 输入：n = 4, k = 9
 * 输出："2314"
 * 示例 3：
 *
 * 输入：n = 3, k = 1
 * 输出："123"
 * 
 *
 * 提示：
 *
 * 1 <= n <= 9
 * 1 <= k <= n!
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/permutation-sequence
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class T66V2 {

    // 阶乘数组
    int[] factorial = null;
    boolean[] used;
    String result = null;
    public String getPermutation(int n, int k) {
        calculateFactorial(n);
        used = new boolean[n+1];
        dfs(n,0,k,new StringBuffer());
        return null;
    }

    public void calculateFactorial(int n){
        factorial = new int[n+1];
        factorial[0] = 1;
        for (int i = 1; i <=n; i++) {
            factorial[i] = factorial[i-1]*i;
        }
    }

    public void dfs(int n,int pos,int k,StringBuffer buffer){
        if (pos == n){
            result = buffer.toString();
            return;
        }
        int fac = factorial[n-1-pos];
        for (int i = 1; i <= n; i++) {
            if (used[i]){
                continue;
            }
            if (fac<k){
                k = k-fac;
                continue;
            }
            buffer.append(i);
            used[i] = true;
            dfs(n,pos+1,k,buffer);
            return;
        }
    }

    public void backtrack(int n,StringBuffer buffer){

    }

    public static void main(String[] args) {
        T66V2 t66 = new T66V2();
        String permutation = t66.getPermutation(4, 9);
        System.out.println(permutation);
    }

}
